package com.example.wx.controller.wx;

import com.example.wx.common.WxConstant;
import com.example.wx.modle.message.Text;
import com.example.wx.util.Obj2XmlUtil;
import com.example.wx.util.SHA1Util;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Slf4j
@RequestMapping(value = "/wx/{appId}")
@RestController
public class WxEventController {

    private static final String LOG_PREFIX = "微信消息-";
    /**
     * @author: ZhangBin
     * @date: 2025/4/2 14:11
     * @description: 微信事件推送
     */
    @GetMapping
    public String doGet(@RequestParam("signature") String signature,
                        @RequestParam("timestamp") String timestamp,
                        @RequestParam("nonce") String nonce,
                        @RequestParam("echostr")String echoStr,
                        @PathVariable("appId")String appId) {
        log.info(LOG_PREFIX+"doGet-appId={}",appId);
        String[] params = new String[]{appId, timestamp, nonce};
        Arrays.sort(params);
        if (SHA1Util.getSha1(String.join(StringUtils.EMPTY, params)).equals(signature)) {
            return echoStr;
        }
        return null;
    }
    /**
     * @author: ZhangBin
     * @date: 2025/4/2 14:11
     * @description: 用户发送过来的信息，关注,取消关注等
     */
    @PostMapping
    public String doPost(HttpServletRequest httpServletRequest, @PathVariable("appId")String appId) throws IOException, DocumentException {
        log.info(LOG_PREFIX+"doPost-appId={}",appId);
        //1.从request获取用户发送过来的信息
        InputStream is = httpServletRequest.getInputStream();
        //2.解析获取到xml为map
        Element element = new SAXReader().read(is).getRootElement();//获取xml文档的根元素
        List<Element> elements = element.elements();//得到xml根元素的所有子节点
        Map<String, String> map = new HashMap<>();//用来存节点和节点内容
        for (Element e : elements) {//遍历子节点，输出为map
            map.put(e.getName(), e.getText());
        }
        //3.输出这些节点和对应的内容
        String msgType = map.get("MsgType");//消息类型
        String event = map.get("Event");//事件类型
        if (WxConstant.EVENT_SUBSCRIBE.equals(event)) {//关注
           log.info("有人关注了你");
            return getText2XMl(map, "感谢关注，祝您生活愉快！");
        } else if (WxConstant.EVENT_UNSUBSCRIBE.equals(event)) {//取消关注
           log.info("有人取消了关注");
        } else if (WxConstant.EVENT_CLICK.equals(event)) {//菜单上面的事件推送(还能判断带有的key值来判断具体是哪一个按钮)
            log.info("有人点了按钮");
        } else if (WxConstant.TEXT.equals(msgType)) {//文本消息
            String content = map.get("Content").trim();//如果是消息类型
            log.info("有人发送了文本消息-content={}",content);
        }
        return getText2XMl(map, "您好，祝您生活愉快！");
    }

    private String getText2XMl(Map<String, String> map, String content) {
        Text text = new Text();
        text.setFromUserName(map.get("ToUserName"));
        text.setToUserName(map.get("FromUserName"));
        text.setMsgType(WxConstant.TEXT);
        text.setCreateTime(new Date().getTime());
        text.setContent(content);
        return Obj2XmlUtil.objToXml(text, WxConstant.XML);
    }
}
